#include "Timer.h"


CTimer::CTimer(uv_loop_t* loop):m_loop(loop)
{
}


CTimer::~CTimer()
{
	if (m_bRumTimer)
	{
		StopTimer();
		m_bRumTimer=false;
	}
}

void CTimer::StartTimer(uint64_t timeout, uint64_t repeat, CbFuncTimer cbTimer, void* userData)
{	
	int nRet = 0;	
	nRet = uv_timer_init(m_loop, &m_uvTimer);
	if (nRet != 0)
	{
		printf("AddTimer uv_timer_init failed[%d][%s]", nRet, uv_strerror(nRet));		
		return;
	}
	m_timercb = cbTimer;
	m_usrData = userData;
	m_uvTimer.data=this;
	nRet = uv_timer_start(&m_uvTimer, CTimer::OnTimer, timeout, repeat);
	m_bRumTimer=true;
}


void CTimer::StopTimer()
{
	if (!m_bRumTimer){return;}
	int nRet = 0;
	nRet = uv_timer_stop(&m_uvTimer);
	if (nRet != 0)
	{
		printf("StopTimer uv_timer_stop failed[%d][%s]", nRet, uv_strerror(nRet));
		return;
	}
	if (0 == uv_is_closing((uv_handle_t*)(&m_uvTimer)))
	{
		uv_close((uv_handle_t*)(&(m_uvTimer)), nullptr);
	}
	printf("Stop one Timer\n");
	m_bRumTimer=false;	
}

void CTimer::OnTimer(uv_timer_t* rTimer)
{
	if ((NULL == rTimer) || (NULL == rTimer->data))
	{
		printf("OnTimer Get NULL uv_timer_t or data");
		return;
	}
	CTimer* timerPtr = (CTimer*)rTimer->data;
	if (timerPtr->m_timercb!= NULL)
	{
		timerPtr->m_timercb(timerPtr->m_usrData);
	}
}
